﻿using System;
using System.Web;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint;
using Microsoft.Office.Word.Server.Conversions;
using System.Web.UI;
using Microsoft.SharePoint.WebControls;

namespace CodeCounsel.StateReports
{
    public class ReportGenerator : UnsecuredLayoutsPageBase
    {
        protected override void OnLoad(EventArgs e)
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            Guid listID = new Guid(Context.Request.QueryString["ListId"]);
            int itemID = Int32.Parse(Context.Request.QueryString["Item"]);
            SPLongOperation.Begin(
                      "Creating reports",
                      "Creating reports2",
                      delegate(SPLongOperation operation)
                      {
                          SPList list = SPContext.Current.Web.Lists.GetList(listID, false);
                          SPListItem item = list.GetItemById(itemID);
                          ReportDataManager dataManager = new ReportDataManager(
                              SPContext.Current.Web, item.File.Url); ;
                          ReportConverter converter = new ReportConverter(
                              SPContext.Current.Web, (SPDocumentLibrary)list, SaveFormat.XPS);
                          foreach (string state in dataManager.GetStates())
                          {
                              string title = dataManager.GetStateReportTitle(state);
                              byte[] image = dataManager.GetStateReport(state);
                              byte[] report = ReportBuilder.CreateReport(title, image, SPContext.Current.Web);
                              converter.AddFile(state, report);
                          }
                          converter.Job.Start();
                          operation.End(list.DefaultViewUrl, SPRedirectFlags.Default, Context, null);
                      });
        }
    }
}
